package cn.net.autocode.files.word;

import org.apache.poi.ooxml.POIXMLDocument;
import org.apache.poi.xwpf.usermodel.*;
import org.jodconverter.core.DocumentConverter;
import org.jodconverter.core.office.OfficeException;
import org.jodconverter.local.LocalConverter;
import org.jodconverter.local.office.LocalOfficeManager;
import org.jodconverter.local.office.LocalOfficeUtils;
import java.io.*;
import java.util.*;
import java.util.List;

public class WordUtils {

    public static void fillWord(String wordFilePath, Map<String,String> map) throws IOException {
        XWPFDocument document = new XWPFDocument(POIXMLDocument.openPackage(wordFilePath));
        //占位符填充
        Iterator<XWPFParagraph> itPara = document.getParagraphsIterator();
        while (itPara.hasNext()) {
            XWPFParagraph paragraph = itPara.next();
            List<XWPFRun> run = paragraph.getRuns();
            for (XWPFRun xwpfRun : run) {
                String key = xwpfRun.getText(xwpfRun.getTextPosition());
                if ( key!= null && !key.isBlank() && map.containsKey(key)) {
                    xwpfRun.setText(map.get(key), 0);
                }
            }
        }

        //table占位符填充
        Iterator<XWPFTable> itTables = document.getTablesIterator();
        while (itTables.hasNext()) {
            XWPFTable table = itTables.next();
            int rcount = table.getNumberOfRows();
            for (int i = 0; i < rcount; i++) {
                XWPFTableRow row = table.getRow(i);
                List<XWPFTableCell> cells = row.getTableCells();
                for (XWPFTableCell cell : cells) {
                    List<XWPFParagraph> paraList = cell.getParagraphs();
                    for (XWPFParagraph paragraph : paraList) {
                        List<XWPFRun> run = paragraph.getRuns();
                        for (XWPFRun xwpfRun : run) {
                            String key = xwpfRun.getText(xwpfRun.getTextPosition());
                            if (key != null && !key.isBlank() && map.containsKey(key)) {
                                xwpfRun.setText(map.get(key), 0);
                            }
                        }
                    }
                }
            }
        }

        //table扩展
        List<XWPFTable> tables = document.getTables();
        XWPFTable secondTable = tables.get(1);
        // 表格的插入行有两种方式，这里使用addNewRowBetween，因为这样会保留表格的样式，就像我们在word文档的表格中插入行一样。注意这里不要使用insertNewTableRow方法插入新行，这样插入的新行没有样式，很难看
        // table.addNewRowBetween(0, 1);
        // 获取到刚刚插入的行
        // int rowNum = secondTable.getRows().size();
        // 设置单元格内容
        for (int i = 0; i <= 10; i++) {

            XWPFTableRow newRow = secondTable.createRow();
            newRow.getCell(0).setText("/" );

            newRow.getCell(1).setText("/");
            newRow.getCell(1).getParagraphs().get(0).setAlignment(ParagraphAlignment.CENTER);//居中

            newRow.getCell(2).setText("/");
            newRow.getCell(2).getParagraphs().get(0).setAlignment(ParagraphAlignment.CENTER);//居中

            newRow.getCell(3).setText("/");
            newRow.getCell(3).getParagraphs().get(0).setAlignment(ParagraphAlignment.CENTER);//居中
        }
    }

    public static void docToPdf(String wordPath, String pdfPath) {
        // 启动Office管理器
        File officeHome = LocalOfficeUtils.getDefaultOfficeHome();
        LocalOfficeManager officeManager = LocalOfficeManager.builder()
                .officeHome(officeHome)
                .install() // 自动安装所需的扩展
                .build();

        try {
            File wordFile = new File(wordPath);
            File pdfFile = new File(pdfPath);
            if (pdfFile.exists()) {
                pdfFile.delete();
            }

            officeManager.start();

            // 创建转换器
            DocumentConverter converter = LocalConverter.builder()
                    .officeManager(officeManager)
                    .build();

            // 执行转换
            converter.convert(wordFile)
                    .to(pdfFile)
                    .execute();

        } catch (OfficeException e) {
            throw new RuntimeException(e);
        } finally {
            if (officeManager != null) {
                try {
                    officeManager.stop();
                } catch (OfficeException e) {
                    throw new RuntimeException(e);
                }
            }

        }
    }

    public static byte[] docToPdf(byte[] wordContents,String fileType) {

        // 启动Office管理器
        File officeHome = LocalOfficeUtils.getDefaultOfficeHome();
        LocalOfficeManager officeManager = LocalOfficeManager.builder()
                .officeHome(officeHome)
                .install() // 自动安装所需的扩展
                .build();

        try {
            File wordTempFile = File.createTempFile(UUID.randomUUID().toString(),fileType);
            FileOutputStream fileOutputStream = new FileOutputStream(wordTempFile);
            fileOutputStream.write(wordContents);

            // 创建临时文件存储PDF内容
            File pdfTempFile = File.createTempFile(UUID.randomUUID().toString(), ".pdf");

            officeManager.start();

            // 创建转换器
            DocumentConverter converter = LocalConverter.builder()
                    .officeManager(officeManager)
                    .build();

            // 执行转换
            converter.convert(wordTempFile)
                    .to(pdfTempFile)
                    .execute();

            // 读取PDF临时文件内容到byte数组
            byte[] pdfBytes;
            try (FileInputStream fis = new FileInputStream(pdfTempFile);
                 ByteArrayOutputStream bos = new ByteArrayOutputStream()) {

                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = fis.read(buffer)) != -1) {
                    bos.write(buffer, 0, bytesRead);
                }
                pdfBytes = bos.toByteArray();
            }
            //删除临时文件
            if (wordTempFile.exists()) {
                wordTempFile.delete();
            }
            if (pdfTempFile.exists()) {
                pdfTempFile.delete();
            }
            return pdfBytes;
        } catch (IOException | OfficeException e) {
            throw new RuntimeException(e);
        } finally {
            // 停止管理器
            if (officeManager != null) {
                try {
                    officeManager.stop();
                } catch (OfficeException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
